﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Belyn.Common.Web
{
    public class DownloadManage:IDownloadManage
    {
        private List<IDownload> _DownloadList;
        public List<IDownload> DownloadList
        {
            get
            {
                if (_DownloadList == null)
                { _DownloadList = new List<IDownload>(); }
                return this._DownloadList;
            }

            set { this._DownloadList = value; }
        }

        public int Count { get { return this.DownloadList.Count; } }

        public DownloadManage()
        {
            DownloadList = new List<IDownload>();
        }


        public virtual void Add(IDownload dl)
        {
            if (this.DownloadList.Contains(dl) == false)
            {
                this.DownloadList.Add(dl);
                this.OnAdded(dl);
                this.OnListChanged(null);
            }
        }

        public virtual void Remove(IDownload dl)
        {
            if (this.DownloadList.Contains(dl) == true)
            {
                this.DownloadList.Remove(dl);
                this.OnRemoved(dl);
                this.OnListChanged(null);
            } 
        }

        public virtual void Clear()
        {
            
            if (this.Count > 0)
            {
                this.DownloadList.Clear();
                 
                this.OnListChanged(null);
            
            } 
                
        }

        public virtual bool Exists(IDownload dl)
        {
            return this.DownloadList.Contains(dl);
        }


        public event EventHandler ListChanged;
        public event DownloadDelegate Added;
        public event DownloadDelegate Removed; 

        protected void OnListChanged(EventArgs args)
        {
            if (this.ListChanged != null)
            {
                this.ListChanged(this, args);
            }
        }

        protected void OnAdded(IDownload d)
        {
            if (this.Added != null)
            {
                this.Added(d);
            }
        }

        protected void OnRemoved(IDownload d)
        {
            if (this.Removed != null)
            {
                this.Removed(d);
            }
        } 

        public void StopAll()
        {
            var ILDownloadForStop = this.DownloadList.ToList();
            foreach (IDownload dl in ILDownloadForStop)
            {
                dl.Stop();
            }
        }

    }
}
